package com.threefire.quickstart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author zhouyanxiang
 * @Date 2021-01-2021/1/9-13:50
 */
public class Server {

    public static void main(String[] args) throws InterruptedException {
        // 1.创建两个线程组 Reactor模型的主从多线程模式
        // boss线程组用于网络连接请求的
        // work线程组用于I/O请求的
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workGroup = new NioEventLoopGroup();
        // 2.通过辅助类去构建 server/client
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 3. 进行Nio Server的配置
        // 3.1 绑定bossGroup和workGroup
        serverBootstrap.group(bossGroup, workGroup)
                // 3.2 server端绑定NioServerSocketChannel
                .channel(NioServerSocketChannel.class)
                // 3.3 设置超时连接，3000ms
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,3000)
                // 3.4 设置TCP backlog参数 = sync队列 + accept队列
                .option(ChannelOption.SO_BACKLOG,1024)
                // 3.5 设置配置项，通配不延迟
                .childOption(ChannelOption.TCP_NODELAY,true)
                // 3.6 设置配置项，接收和发送缓冲区大小
                .childOption(ChannelOption.SO_RCVBUF,1024 * 32)
                .childOption(ChannelOption.SO_SNDBUF,1024 * 32)
                // 3.7 进行初始化ChannelInitializer，用于构建双向链表"pipeline"添加业务handler处理
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 3.8 这里仅仅针对一个业务处理器ServerHandler(后面我们要对它进行编码)
                        socketChannel.pipeline().addLast();
                    }
                });
        // 4.服务端绑定端口并启动服务 使用channel级别的监听close端口 阻塞的方式
        ChannelFuture channelFuture = serverBootstrap.bind(8765).sync();
        channelFuture.channel().closeFuture().sync();

        // 5.关闭资源
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

}
